package dbext

import (
	"gitee.com/tjloved/tool"
	"github.com/pkg/errors"
)

// 数据表同步
type TableSyncer struct {
	columnComparator *ColumnComparator
}

func NewTableSyncer() *TableSyncer {
	return &TableSyncer{columnComparator: &ColumnComparator{}}
}

func (ts *TableSyncer) Sync(originalTable string, originalConnection string, dstTable string, dstConnection string) error {
	if false == tool.Db(originalConnection).Migrator().HasTable(originalTable) {
		return errors.Errorf("originalTable %s.%s not exist", originalConnection, originalTable)
	}
	if false == tool.Db(dstConnection).Migrator().HasTable(dstTable) {
		var createSqlData map[string]interface{}
		if db := tool.Db(originalConnection).Raw("show create table " + originalTable).First(&createSqlData); db.Error != nil {
			return db.Error
		}
		createSqlStr := createSqlData["Create Table"].(string)
		if db := tool.Db(dstConnection).Exec(createSqlStr); db.Error != nil {
			return db.Error
		}
	} else {
		ddlSlice := ts.columnComparator.Compare(originalTable, originalConnection, dstTable, dstConnection).ToDDLString()
		for _, ddl := range ddlSlice {
			if ddl != "" {
				if db := tool.Db(dstConnection).Exec(ddl); db.Error != nil {
					return db.Error
				}
			}
		}
	}
	return nil
}
